//进行axios的二次封装：使用请求与响应拦截器
import axios from "axios";
//利用axios对象的create方法创建axios实例（其他配置：基础路径、超时时间。。。）
import useUserStore from "../store/modules/user";

let request = axios.create({
  //基础路径
  baseURL: " http://127.0.0.1:8000", //基础路径携带
  timeout: 5000,
});

//请求拦截器
request.interceptors.request.use((config) => {
  //获取token后
  let userStore = useUserStore();

  //config配置对象，有header属性请求头
  if (userStore.token) {
    config.headers.token = userStore.token;
  }
  return config;
});

//响应拦截器
request.interceptors.response.use(
  (response) => {
    //成功回调
    return response.data;
  },
  (error) => {
    console.log(error);
    //处理网络错误
    let msg = "";
    let status = error.response.status;
    switch (status) {
      case 400:
        msg = "密码或账户错误！";
        break;
      case 401:
        msg = "token过期";
        break;
      case 403:
        msg = "无权访问";
        break;
      case 404:
        msg = "请求地址错误";
        break;
      case 500:
        msg = "服务器出现问题";
        break;
      default:
        msg = "无网络";
    }

    return Promise.reject(error);
  }
);
export default request;
